var mongoose = require('mongoose');
//var $ = require('jquery');
var _ = require('lodash/core');
//var Hospital = mongoose.model('Hospital');
var Doctor = mongoose.model('Doctor');

function trimJSONStr(jStr){
  return JSON.stringify(JSON.parse(jStr));
}

module.exports.createDoctor = function(docData,cb){
  console.log('Doctor.dao:createDoctor...',JSON.stringify(docData,null,2));
  //var model = docData.model;
  //create a Doctor document here.
  
  /*
   {
    hcode:docData.hcode,
    name: docData.name,
    address: docData.address,
    gpsinfo: docData.gpsinfo,
    introduction: docData.introduction
  }
   * */
  Doctor.create(docData, function(err, doctor) {
    console.log('create callback.');
    if (err) {
      console.log(err);
      //res.status(406).json(err);
      if(cb) cb(err,null);
      return;
    }
    if(cb) cb(null,doctor);
  });
  console.log('createDoctor over');
};

module.exports.updateDoctor = function(did,docData,cb){
  console.log('updateDoctor-docData:',JSON.stringify(docData,null,2));
  //update Doctor here:
  Doctor.findById(did).exec(function(err, doctor) {
    if(err){
      console.error(err);
      if(cb) cb(err,null);
      return;
    }
    console.log('docData',JSON.stringify(docData,null,2));
    var _docData = _.assignIn(docData,{updatedOn:Date.now()});
    
    console.log('_docData',JSON.stringify(_docData,null,2));
    
    /*
     {
      hcode:docData.hcode,
      name: docData.name,
      address: docData.address,
      gpsinfo: docData.gpsinfo,
      introduction: docData.introduction,
      updatedOn:Date.now()
    }
    */
    doctor.update(_docData,function(err, doctor) {
      if (err) {
        console.log(err);
        if(cb) cb(err,null);
        //res.status(406).json('update failed:'+err);
      }
      if(cb) cb(null,doctor);
    });
  });
};

module.exports.removeDoctor = function(did,cb){
  Doctor.findById(did).exec(function(err, doctor) {
    if (err) {
      console.log(err);
      if(cb) cb(err,null);
      return;
    }
    //doctor.save(function(err,updateDoctor){
    	doctor.remove(function(err,updateDoctor){
      if(err){
        console.log(err);
        if(cb) cb(err,null);
        return;
      }
      if(cb) cb(null,did);
    });
  });
};

module.exports.getDoctorList = function(filter,limit,cb){
  Doctor.find(filter||{dtype:'doctor'}).limit(limit||20).
    select('name worktel dtype introduction homeaddress homegps servicetime servicerange').
    exec(function(err, rows) {
      console.log('in dao:',rows.length);
      if (err) {
        console.log(err);
        if(cb) cb(err,null);
        return;
      }
      if(cb) cb(null,rows);
    });
};

module.exports.getDoctor = function(did,cb){
  Doctor.findById(did).exec(function(err, doctor) {
    if (err) {
      console.log(err);
      if(cb) cb(err,null);
      return;
    }
    if(cb) cb(null,doctor);
  });
};
